package com.wfx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jwt.util.SendMessageUtil;
import com.jwt.util.VerifyCodeUtil;
import com.wfx.entity.Result;
import com.wfx.entity.WxbCustomer;
import com.wfx.entity.WxbMemeber;
import com.wfx.mapper.WxbCustomerMapper;
import com.wfx.mapper.WxbMemeberMapper;
import com.wfx.service.ISendCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SendCodeServiceImpl implements ISendCodeService {
    @Autowired
    private WxbMemeberMapper wxbMemeberMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //发送验证码
    public Result sendCode(String phone){
        //根据手机号码获取用户信息
        QueryWrapper<WxbMemeber> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        WxbMemeber wxbMemeber = wxbMemeberMapper.selectOne(queryWrapper);
        if (wxbMemeber == null) {
            return  new Result(false,"手机号码不存在");
        }else{

            //随机产生4位数的验证码
            String code = VerifyCodeUtil.generateVerifyCode(4, "abcdqwertyuiop8912345672wqwe");
            //发送短信
            boolean success = SendMessageUtil.sendMsg(phone, code);
            if(success){
                //发送成功,将code保存到redis中
                String key = phone;
                System.out.println(key);
                stringRedisTemplate.boundValueOps(key).set(code);

                stringRedisTemplate.expire(key,60, TimeUnit.MINUTES);

                System.out.println(stringRedisTemplate.boundValueOps(key).get());
                return  new Result(true,"发送成功");
            }else{
                return  new Result(false,"短信发送失败");

            }

        }

    }
}
